"""
图书搜索功能测试
测试图书的关键字搜索功能
"""

import requests
import json

base_url = "http://localhost:8080/api"
books_url = f"{base_url}/books"


def test_books_info():
    """测试获取图书接口信息"""
    print("=== 测试获取图书接口信息 ===")

    try:
        response = requests.get(f"{books_url}/")

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")

        if response.status_code == 200:
            print("✅ 获取图书接口信息成功")
            return True
        else:
            print("❌ 获取图书接口信息失败")
            return False

    except Exception as e:
        print(f"❌ 获取图书接口信息请求异常: {e}")
        return False


def test_get_book_detail(book_id=1):
    """测试获取图书详情"""
    print(f"\n=== 测试获取图书详情 (book_id: {book_id}) ===")

    try:
        response = requests.get(f"{books_url}/get", params={"book_id": book_id})

        print(f"状态码: {response.status_code}")
        response_data = response.json()
        print(f"响应内容: {json.dumps(response_data, ensure_ascii=False, indent=2)}")

        if response.status_code == 200:
            print("✅ 获取图书详情成功")
            if "book_data" in response_data:
                book = response_data["book_data"]
                print(f"图书标题: {book.get('title', 'N/A')}")
                print(f"图书作者: {book.get('author', 'N/A')}")
                print(f"图书评分: {book.get('rating', 'N/A')}")
            return True
        else:
            print("❌ 获取图书详情失败")
            return False

    except Exception as e:
        print(f"❌ 获取图书详情请求异常: {e}")
        return False


def test_search_books(keyword="python", page=1, limit=10):
    """测试搜索图书"""
    print(f"\n=== 测试搜索图书 (keyword: {keyword}, page: {page}, limit: {limit}) ===")

    try:
        params = {"q": keyword, "page": page, "limit": limit}
        response = requests.get(f"{books_url}/search", params=params)

        print(f"状态码: {response.status_code}")
        response_data = response.json()
        print(f"响应内容: {json.dumps(response_data, ensure_ascii=False, indent=2)}")

        if response.status_code == 200:
            print("✅ 搜索图书成功")
            print(f"总图书数: {response_data.get('total', 0)}")
            print(f"当前页图书数量: {len(response_data.get('books_list', []))}")

            # 显示搜索结果
            books = response_data.get("books_list", [])
            for i, book in enumerate(books, 1):
                print(
                    f"  {i}. {book.get('title', 'N/A')} - {book.get('author', 'N/A')} (评分: {book.get('rating', 'N/A')})"
                )

            return True
        else:
            print("❌ 搜索图书失败")
            return False

    except Exception as e:
        print(f"❌ 搜索图书请求异常: {e}")
        return False


def test_search_variations():
    """测试不同关键字的搜索"""
    print("\n=== 测试不同关键字的搜索 ===")

    # 测试不同的搜索关键字
    search_keywords = [
        "python",
        "算法",
        "编程",
        "数据结构",
        "人工智能",
        "机器学习",
        "深度学习",
        "计算机",
        "软件工程",
    ]

    success_count = 0

    for keyword in search_keywords:
        print(f"\n测试搜索关键字: {keyword}")
        if test_search_books(keyword, page=1, limit=5):
            success_count += 1

    print(f"\n✅ 搜索关键字测试完成，成功: {success_count}/{len(search_keywords)}")
    return success_count == len(search_keywords)


def test_search_pagination():
    """测试搜索分页功能"""
    print("\n=== 测试搜索分页功能 ===")

    keyword = "编程"

    # 测试第一页
    print(f"测试第一页 (keyword: {keyword})")
    first_page = test_search_books(keyword, page=1, limit=5)

    if first_page:
        # 测试第二页
        print(f"\n测试第二页 (keyword: {keyword})")
        second_page = test_search_books(keyword, page=2, limit=5)

        if second_page:
            print("✅ 搜索分页功能测试成功")
            return True
        else:
            print("⚠️ 第二页测试失败（可能是数据不足）")
            return True  # 第一页成功就算通过
    else:
        print("❌ 搜索分页功能测试失败")
        return False


def test_search_edge_cases():
    """测试搜索边界情况"""
    print("\n=== 测试搜索边界情况 ===")

    # 测试空关键字
    print("测试空关键字:")
    try:
        response = requests.get(f"{books_url}/search", params={"q": ""})
        print(f"空关键字搜索 - 状态码: {response.status_code}")
    except Exception as e:
        print(f"空关键字搜索异常: {e}")

    # 测试很长的关键字
    print("\n测试很长的关键字:")
    long_keyword = "这是一个非常非常长的搜索关键字用来测试系统的边界情况处理能力"
    test_search_books(long_keyword, limit=3)

    # 测试特殊字符
    print("\n测试特殊字符:")
    special_keywords = ["C++", "C#", ".NET", "JavaScript", "Node.js"]
    for keyword in special_keywords:
        print(f"搜索特殊关键字: {keyword}")
        test_search_books(keyword, limit=3)

    print("✅ 边界情况测试完成")


def test_search_performance():
    """测试搜索性能"""
    print("\n=== 测试搜索性能 ===")

    import time

    keyword = "编程"
    test_count = 5
    total_time = 0

    print(f"执行 {test_count} 次搜索测试...")

    for i in range(test_count):
        start_time = time.time()
        try:
            response = requests.get(
                f"{books_url}/search", params={"q": keyword, "limit": 10}
            )
            end_time = time.time()

            if response.status_code == 200:
                duration = end_time - start_time
                total_time += duration
                print(f"第 {i+1} 次搜索耗时: {duration:.3f}秒")
            else:
                print(f"第 {i+1} 次搜索失败")

        except Exception as e:
            print(f"第 {i+1} 次搜索异常: {e}")

    if total_time > 0:
        avg_time = total_time / test_count
        print(f"平均搜索耗时: {avg_time:.3f}秒")
        if avg_time < 1.0:
            print("✅ 搜索性能良好")
        else:
            print("⚠️ 搜索性能可能需要优化")


def run_all_search_tests():
    """运行所有搜索测试"""
    print("开始图书搜索功能测试...")
    print("=" * 80)

    # 1. 测试图书接口信息
    test_books_info()

    # 2. 测试获取图书详情
    test_get_book_detail()

    # 3. 测试基本搜索功能
    test_search_books("python")

    # 4. 测试不同关键字搜索
    test_search_variations()

    # 5. 测试分页功能
    test_search_pagination()

    # 6. 测试边界情况
    test_search_edge_cases()

    # 7. 测试性能
    test_search_performance()

    print("\n" + "=" * 80)
    print("图书搜索功能测试完成")


if __name__ == "__main__":
    run_all_search_tests()
